#!/bin/bash

# Docker网络问题解决方案脚本
# 解决Docker Hub连接超时问题

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Docker网络问题解决方案${NC}"
echo -e "${BLUE}========================================${NC}"

# 检查Docker服务状态
echo -e "${YELLOW}检查Docker服务状态...${NC}"
if ! systemctl is-active --quiet docker; then
    echo -e "${RED}Docker服务未运行，正在启动...${NC}"
    sudo systemctl start docker
    sudo systemctl enable docker
fi

# 检查网络连接
echo -e "${YELLOW}检查网络连接...${NC}"
if ! ping -c 1 registry-1.docker.io &> /dev/null; then
    echo -e "${RED}无法连接到Docker Hub，使用国内镜像源...${NC}"
    
    # 创建Docker配置目录
    sudo mkdir -p /etc/docker
    
    # 配置国内镜像源
    echo -e "${GREEN}配置国内镜像源...${NC}"
    sudo tee /etc/docker/daemon.json > /dev/null <<EOF
{
  "registry-mirrors": [
    "https://registry.cn-hangzhou.aliyuncs.com",
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com",
    "https://mirror.ccs.tencentyun.com"
  ],
  "max-concurrent-downloads": 10,
  "max-concurrent-uploads": 5
}
EOF
    
    # 重启Docker服务
    echo -e "${GREEN}重启Docker服务...${NC}"
    sudo systemctl daemon-reload
    sudo systemctl restart docker
    
    # 等待Docker启动
    sleep 5
fi

# 测试镜像拉取
echo -e "${YELLOW}测试镜像拉取...${NC}"
if docker pull hello-world &> /dev/null; then
    echo -e "${GREEN}镜像拉取成功！${NC}"
else
    echo -e "${RED}镜像拉取失败，尝试手动拉取...${NC}"
fi

# 显示当前配置
echo -e "${BLUE}当前Docker配置：${NC}"
sudo cat /etc/docker/daemon.json 2>/dev/null || echo "使用默认配置"

echo
echo -e "${GREEN}解决方案完成！${NC}"
echo -e "${YELLOW}现在可以使用以下命令启动服务：${NC}"
echo "1. 使用国内镜像源："
echo "   docker-compose -f docker-compose-china.yml up -d"
echo "2. 或者先拉取镜像再启动："
echo "   docker-compose pull"
echo "   docker-compose up -d"
echo "3. 手动拉取镜像："
echo "   docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/mysql:8.0"
echo "   docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/redis:7-alpine"